# Authors: Marinho Brandao <marinho at gmail.com>
#          Guilherme M. Gondim (semente) <semente at taurinus.org>
# File: <your project>/admin/filterspecs.py

from django.db import models
from django.contrib.admin.filterspecs import FilterSpec, ChoicesFilterSpec
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext as _
from adl.guild.models import Character

class AlphabeticFilterSpec(ChoicesFilterSpec):
    """
    Adds filtering by first char (alphabetic style) of values in the admin
    filter sidebar. Set the alphabetic filter in the model field attribute
    'alphabetic_filter'.

    my_model_field.alphabetic_filter = True
    """

    def __init__(self, f, request, params, model, model_admin):
        super(AlphabeticFilterSpec, self).__init__(f, request, params, model,
                                                   model_admin)
        self.lookup_kwarg = '%s__istartswith' % f.name
        self.lookup_val = request.GET.get(self.lookup_kwarg, None)
        
        values_list = model.objects.values_list(f.name, flat=True)
        
        # getting the first char of values
        self.lookup_choices = list(set(val[0] for val in values_list))
        self.lookup_choices.sort()


    def choices(self, cl):
        yield {'selected': self.lookup_val is None,
                'query_string': cl.get_query_string({}, [self.lookup_kwarg]),
                'display': _('All')}
        for val in self.lookup_choices:
            yield {'selected': smart_unicode(val) == self.lookup_val,
                    'query_string': cl.get_query_string({self.lookup_kwarg: val}),
                    'display': val.upper()}
    def title(self):
        return _('%(field_name)s that starts with') % \
            {'field_name': self.field.verbose_name}

# registering the filter
FilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'alphabetic_filter', False), AlphabeticFilterSpec))

class LevelGroupFilterSpec(ChoicesFilterSpec):
    """
    Adds filtering by first char (alphabetic style) of values in the admin
    filter sidebar. Set the alphabetic filter in the model field attribute
    'alphabetic_filter'.

    my_model_field.alphabetic_filter = True
    """

    def __init__(self, f, request, params, model, model_admin):
        super(LevelGroupFilterSpec, self).__init__(f, request, params, model,
                                                   model_admin)        
        self.field_generic = '%s__' % self.field.name
        
        self.lookup_min = '%s__gte' % f.name
        self.lookup_max = '%s__lte' % f.name
        
        self.lookup_val = request.GET.get(self.lookup_min, None)
        
        values_list = model.objects.values_list(f.name, flat=True)
        # getting the level range
        # self.lookup_choices = list(set(val for val in values_list))
        # self.lookup_choices.sort()
        max_level = Character.objects.all().order_by('-level')[0].level
        q = [(i*10+11) for i in range(max_level/10)]
        # self.lookup_choices = (11, 21, 31, 41, 51, 61, 71)
        self.lookup_choices = tuple([(i*10+11) for i in range(max_level/10)])
        
        self.param_dict = {}
        for val in self.lookup_choices:       
            self.param_dict.update(
                {val: {
                    '%s__gte' % f.name: val,
                    '%s__lte' % f.name: val + 9
                }}
            )

    def choices(self, cl):
        yield {'selected': self.lookup_val is None,
                'query_string': cl.get_query_string({}, [self.lookup_min, self.lookup_max]),
                'display': _('All')}
        for val in self.lookup_choices:
            yield {'selected': smart_unicode(val) == self.lookup_val,
                    'query_string': cl.get_query_string(self.param_dict[val], [self.field_generic]),
                    'display': '%s - %s' % (val, val+9)}
    def title(self):
        return _('%(field_name)s that is between') % {'field_name': self.field.verbose_name}

# registering the filter
FilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'levelgroup_filter', False), LevelGroupFilterSpec))